import { clearObjectValue, setObjectValue } from '@/utils';

/**
 * @typedef {object} ReturnType
 * @property {object} attrs 属性对象
 * @property {Function} handleOpen 弹框打开方法
 * @property {Function} handleCancel 弹框取消方法
 * @property {() => Promise} confirmForm 确认方法
 */

/**
 * dialog 弹框封装方法
 * @param {object} config
 * @param {object} config.form 表单值
 * @param {object} config.formRef 表单对象
 * @returns {ReturnType} ResultType 返回对象
 */
export const useDialog = (config = {}) => {
  const { form, formRef } = config;
  const attrs = useAttrs();

  const handleOpen = () => {
    const { row } = attrs || {};
    if (row) {
      setObjectValue(form.value, row);
    }
  };

  const handleCancel = () => {
    clearObjectValue(form.value);
    formRef.value.resetFields();
  };

  const confirmForm = () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate(valid => {
        if (valid) {
          resolve();
        } else {
          reject();
        }
      });
    });
  };
  return {
    attrs,
    handleOpen,
    handleCancel,
    confirmForm,
  };
};
